package org.devgframwork.demo.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class ProducerDemo {

    public static void main(String[] args) throws InterruptedException {

        KafkaProducer<String, String> kafkaProducer = getKafkaProducer();
        for (int i = 0; i < 100; i++) {
            // 发送数据 ,需要一个producerRecord对象,
            // 最少参数 String topic,V value
            ProducerRecord producerRecord = new ProducerRecord<String, String>("mytopic", "订单信息！" + i);
            kafkaProducer.send(producerRecord);
            Thread.sleep(100);
        }
        kafkaProducer.close();
    }


    private static KafkaProducer<String, String> getKafkaProducer() {

        /* 1、连接集群，通过配置文件的方式
         * 2、发送数据-topic:mytopic，value
         */
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
        props.put(ProducerConfig.ACKS_CONFIG, "all");
        props.put(ProducerConfig.RETRIES_CONFIG, 0);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16834);
        props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(props);
        return kafkaProducer;
    }
}
